﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections;
using System.Text;
using System.Globalization;

namespace WebArchivosTelefonica.Jerarquias
{
   /// <summary>
   /// Message Box para web
   /// </summary>
   public sealed class WebMsgBox
   {
      /// <summary>
      /// 
      /// </summary>
      private static Hashtable handlerPages;// = new Hashtable();

      private WebMsgBox()
      {
          handlerPages = new Hashtable();
      }

      /// <summary>
      /// Muestra un message box en la pagina actual
      /// </summary>
      /// <param name="message">Mensaje a mostrar</param>
      public static void Show(string message)
      {

         if (!(handlerPages.Contains(HttpContext.Current.Handler)))
         {

            Page currentPage = (Page)HttpContext.Current.Handler;

            if (!((currentPage == null)))
            {

               Queue messageQueue = new Queue();

               messageQueue.Enqueue(message);

               handlerPages.Add(HttpContext.Current.Handler, messageQueue);

               currentPage.Unload += new EventHandler(CurrentPageUnload);

            }

         }

         else
         {

            Queue queue = ((Queue)(handlerPages[HttpContext.Current.Handler]));

            queue.Enqueue(message);

         }

      }

      /// <summary>
      /// Crea el javascript para mostrar el message box
      /// </summary>
      /// <param name="sender"></param>
      /// <param name="e"></param>
      private static void CurrentPageUnload(object sender, EventArgs e)
      {

         Queue queue = ((Queue)(handlerPages[HttpContext.Current.Handler]));

         if (queue != null)
         {

            StringBuilder builder = new StringBuilder();

            int iMsgCount = queue.Count;

            builder.Append("<script language='javascript'>");

            string sMsg;

            while ((iMsgCount > 0))
            {

               iMsgCount = iMsgCount - 1;

               sMsg = System.Convert.ToString(queue.Dequeue(),CultureInfo.CurrentCulture);

               sMsg = sMsg.Replace("\"", "'");

               builder.Append("alert( \"" + sMsg + "\" );");

            }

            builder.Append("</script>");

            handlerPages.Remove(HttpContext.Current.Handler);

            HttpContext.Current.Response.Write(builder.ToString());

         }

      }

   } 
}
